<template>
  <!-- 无障碍设施地图标记组件 -->
  <!-- 提供地图显示、设施标记、信息弹窗等功能 -->
  <view class="map-container">
    <!-- 高德地图容器，用于初始化地图 -->
    <view ref="mapContainer" class="amap-container"></view>
    
    <!-- 地图工具按钮区 -->
    <view class="map-tools">
      <!-- 2D/3D视图切换按钮 -->
      <view class="tool-btn" @click="toggleViewMode">
        <view class="icon-svg" v-html="viewMode === '3D' ? generalIcons.view3d : generalIcons.view2d"></view>
      </view>
      <!-- 定位按钮，用于定位到用户当前位置 -->
      <view class="tool-btn" @click="locateCurrentPosition">
        <view class="icon-svg" v-html="generalIcons.locate"></view>
      </view>
      <!-- 添加设施按钮 -->
      <view class="tool-btn add-btn" @click="showAddMarker">
        <view class="icon-svg" v-html="generalIcons.add"></view>
      </view>
    </view>
    
    <!-- 天气信息提示条，可关闭 -->
    <view class="weather-tips" v-if="showWeatherTips">
      <text>今天17:00有雨, 请带伞出行</text>
      <text class="close-btn" @click="closeWeatherTips">×</text>
    </view>
    
    <!-- 设施类型选择弹窗，添加设施时显示 -->
    <view class="facility-select-modal" v-if="showFacilitySelect">
      <view class="facility-select-content">
        <view class="modal-title">选择设施类型</view>
        <view class="facility-types">
          <!-- 遍历显示所有设施类型选项 -->
          <view class="facility-type-item" v-for="type in facilityTypes" :key="type.value" @click="selectFacilityType(type)">
            <view class="facility-icon" v-html="getSvgIcon(type.value)"></view>
            <text class="facility-name">{{ type.name }}</text>
          </view>
        </view>
        <view class="modal-actions">
          <button @click="cancelAddMarker" class="cancel-btn">取消</button>
        </view>
      </view>
    </view>
    
    <!-- 设施详情弹窗，点击标记时显示 -->
    <view class="facility-detail-modal" v-if="showFacilityDetail">
      <view class="facility-detail-content">
        <view class="modal-title">设施详情</view>
        <view class="facility-detail-info">
          <!-- 显示设施名称，如果没有则显示类型名称 -->
          <text class="facility-detail-name">{{ selectedFacility.name || facilityTypeMap[selectedFacility.type].name }}</text>
          <text class="facility-detail-desc">{{ selectedFacility.description || '暂无描述' }}</text>
          <text class="facility-detail-location">位置: {{ selectedFacility.address || '未知位置' }}</text>
        </view>
        <view class="modal-actions">
          <button @click="editFacility" class="edit-btn">编辑</button>
          <button @click="deleteFacility" class="delete-btn">删除</button>
          <button @click="closeFacilityDetail" class="close-btn">关闭</button>
        </view>
      </view>
    </view>
    
    <!-- 设施编辑弹窗，编辑或新增设施时显示 -->
    <view class="facility-edit-modal" v-if="showFacilityEdit">
      <view class="facility-edit-content">
        <view class="modal-title">{{ isEditingFacility ? '编辑设施' : '新增设施' }}</view>
        <view class="facility-edit-form">
          <view class="form-item">
            <text class="form-label">设施名称</text>
            <input class="form-input" v-model="editingFacility.name" placeholder="请输入设施名称" />
          </view>
          <view class="form-item">
            <text class="form-label">设施描述</text>
            <textarea class="form-textarea" v-model="editingFacility.description" placeholder="请输入设施描述" />
          </view>
        </view>
        <view class="modal-actions">
          <button @click="saveFacility" class="save-btn">保存</button>
          <button @click="cancelEdit" class="cancel-btn">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 引入高德地图加载器，用于加载高德地图API
import AMapLoader from '@amap/amap-jsapi-loader';
// 引入设施管理存储，用于管理无障碍设施数据
import { useFacilityStore } from '../store/facilityStore';
// 引入Pinia状态转换工具
import { storeToRefs } from 'pinia';
// 引入SVG图标资源
import { facilityIcons, generalIcons } from '../static/icons/icon-svg';

export default {
  name: 'SimpleMapMarker', // 组件名称
  
  // 使用组合式API设置Pinia状态存储
  setup() {
    // 初始化设施存储
    const facilityStore = useFacilityStore();
    // 获取响应式引用的设施列表和当前视图模式
    const { facilities, currentViewMode } = storeToRefs(facilityStore);
    
    return {
      facilityStore,
      facilities,     // 设施列表数据
      currentViewMode // 当前地图视图模式(2D/3D)
    };
  },
  
  // 组件数据
  data() {
    return {
      map: null,                // 高德地图实例
      mapLoaded: false,         // 地图是否加载完成
      viewMode: '2D',           // 地图视图模式，默认2D
      markers: {},              // 存储地图上的标记点，键为设施ID
      showFacilitySelect: false, // 是否显示设施类型选择弹窗
      showFacilityDetail: false, // 是否显示设施详情弹窗
      showFacilityEdit: false,  // 是否显示设施编辑弹窗
      showWeatherTips: true,    // 是否显示天气提示
      selectedFacility: null,   // 当前选中的设施
      editingFacility: {        // 当前编辑的设施
        name: '',
        description: '',
        type: '',
        position: null
      },
      isEditingFacility: false, // 是否为编辑模式（否则为新增模式）
      clickPosition: null,      // 地图点击位置坐标
      facilityIcons: facilityIcons, // 设施图标SVG
      generalIcons: generalIcons,   // 通用图标SVG
      // 设施类型定义
      facilityTypes: [
        { name: '无障碍坡道', value: 'ramp' },
        { name: '无障碍卫生间', value: 'toilet' },
        { name: '无障碍电梯', value: 'elevator' },
        { name: '爱心停车位', value: 'parking' },
        { name: '爱心点位', value: 'point' },
        { name: '盲道', value: 'blindWay' }
      ],
      facilityTypeMap: {},      // 设施类型映射表，用于快速查找
      staticMapContainer: null, // 静态地图容器引用
      mapPlaceholder: null,      // 地图加载占位符引用
      mapError: '',            // 地图加载错误信息
      amapKey: 'f57e2abaddbd87e3af64c7b3ab4c9d86', // 高德地图API密钥
      current3DMode: false,     // 当前是否为3D模式
      staticMapImg: null,       // 静态地图图片引用
      geoLoading: false,         // 地理编码加载状态
      currentAddress: '',       // 当前获取的地址
      newFacility: null,         // 新添加的设施
      showingFacilityDetail: false, // 是否正在显示设施详情
      showingFacilityTypeModal: false, // 是否正在显示设施类型选择模态框
      currentAddress: '',       // 当前获取的地址
      markerCluster: null        // 标记点聚合实例
    };
  },
  
  created() {
    // 转换facilityTypes为map形式以便快速查找
    // 这样可以通过type.value直接获取type对象，提高检索效率
    this.facilityTypeMap = {};
    this.facilityTypes.forEach(type => {
      this.facilityTypeMap[type.value] = type;
    });
  },
  
  mounted() {
    // 组件挂载后初始化地图
    
    // 创建一个空的错误提示元素作为加载占位符
    if (this.$refs.mapContainer) {
      this.createErrorPlaceholder();
    }
    
    // 从存储中加载已有的设施数据
    this.facilityStore.loadFacilitiesFromStorage();
    
    // 使用setTimeout确保DOM已完全渲染后再加载地图
    setTimeout(() => {
      // 记录地图加载开始时间，用于性能监控
      console.log('开始页面加载时间:', new Date().toLocaleTimeString());
      
      // 先加载静态地图作为底图，提供基础显示，优化用户体验
      this.loadStaticMap();
      
      // 延迟加载动态地图，减轻初始化负担，提高页面响应速度
      setTimeout(() => {
        console.log('开始加载动态地图时间:', new Date().toLocaleTimeString());
        this.initMap();
      }, 800); // 延迟800ms加载动态地图
    }, 300); // 延迟300ms确保DOM已渲染
  },
  
  methods: {
    // 创建地图加载中的占位符，提供视觉反馈
    createErrorPlaceholder() {
      const placeholder = document.createElement('div');
      placeholder.className = 'map-placeholder';
      placeholder.style.width = '100%';
      placeholder.style.height = '100%';
      placeholder.style.backgroundColor = '#f5f5f5';
      placeholder.style.display = 'flex';
      placeholder.style.alignItems = 'center';
      placeholder.style.justifyContent = 'center';
      placeholder.style.color = '#999';
      placeholder.style.fontSize = '14px';
      placeholder.textContent = '地图加载中...';
      
      // 存储引用以便后续移除
      this.mapPlaceholder = placeholder;
      
      // 添加到地图容器
      this.$refs.mapContainer.appendChild(placeholder);
    },
    
    // 移除地图加载占位符
    removePlaceholder() {
      if (this.mapPlaceholder && this.$refs.mapContainer) {
        try {
          this.$refs.mapContainer.removeChild(this.mapPlaceholder);
          this.mapPlaceholder = null;
        } catch (e) {
          console.warn('移除占位符失败:', e);
        }
      }
    },
    
    // 初始化高德地图
    initMap() {
      // 检查高德地图脚本是否已加载，避免重复加载
      if (window.AMap) {
        try {
          // 清除任何已存在的地图实例，防止内存泄漏
          if (this.map) {
            this.map.destroy();
            this.map = null;
          }
          
          // 创建新的地图实例，设置中心点、缩放级别和视图模式
          this.map = new window.AMap.Map(this.$refs.mapContainer, {
            center: [116.39, 39.9], // 默认中心点为北京
            zoom: 13,              // 默认缩放级别
            viewMode: this.current3DMode ? '3D' : '2D', // 根据用户设置决定2D或3D视图
            pitch: this.current3DMode ? 50 : 0,  // 3D模式下的倾斜角度
          });
          
          // 添加地图控制组件：比例尺、定位按钮和地图类型切换
          this.map.addControl(new window.AMap.Scale());
          this.map.addControl(new window.AMap.ToolBar());
          this.map.addControl(new window.AMap.MapType());
          
          // 注册地图点击事件，用于添加新设施
          this.map.on('click', this.handleMapClick);
          
          // 移除加载占位符，显示实际地图
          this.removePlaceholder();
          
          // 记录地图加载完成时间，用于性能监控
          console.log('地图加载完成时间:', new Date().toLocaleTimeString());
          
          // 加载地图完成后，添加已有设施标记
          this.loadFacilities();
          
          // 获取当前位置并在地图上标记
          this.getCurrentPosition();
          
          // 移除错误提示（如果存在）
          if (this.mapError) {
            this.mapError = '';
          }
        } catch (error) {
          // 捕获并记录地图初始化过程中的错误
          console.error('地图初始化失败:', error);
          this.mapError = `地图初始化失败: ${error.message || '未知错误'}`;
        }
      } else {
        // 高德地图API未加载，记录错误并提示用户
        console.error('AMap未加载');
        this.mapError = 'AMap地图API未加载，请检查网络连接或刷新页面重试';
        
        // 5秒后尝试重新加载地图
        setTimeout(() => {
          this.loadExternalScript();
        }, 5000);
      }
    },
    
    // 加载静态地图作为初始底图
    loadStaticMap() {
      // 检查地图容器是否存在
      if (!this.$refs.mapContainer) {
        console.warn('地图容器未找到');
        return;
      }
      
      try {
        // 创建静态地图图片
        const staticMapImg = document.createElement('img');
        staticMapImg.style.width = '100%';
        staticMapImg.style.height = '100%';
        staticMapImg.style.objectFit = 'cover';
        
        // 设置静态地图URL，包含中心点、缩放级别等参数
        const baseUrl = 'https://restapi.amap.com/v3/staticmap';
        const params = new URLSearchParams({
          key: this.amapKey,
          location: '116.39,39.9', // 默认中心点为北京
          zoom: 13,               // 默认缩放级别
          size: '1000*1000',      // 地图图片尺寸
          scale: 2                // 高清图片
        });
        
        staticMapImg.src = `${baseUrl}?${params.toString()}`;
        
        // 设置加载错误处理函数
        staticMapImg.onerror = () => {
          console.warn('静态地图加载失败');
          // 移除加载占位符，显示错误信息
          this.removePlaceholder();
          this.mapError = '静态地图加载失败，尝试加载动态地图...';
        };
        
        // 存储静态地图引用，以便后续移除
        this.staticMapImg = staticMapImg;
        
        // 添加静态地图到容器
        this.$refs.mapContainer.appendChild(staticMapImg);
      } catch (error) {
        // 捕获并记录静态地图加载过程中的错误
        console.error('静态地图加载失败:', error);
        this.mapError = `静态地图加载失败: ${error.message || '未知错误'}`;
      }
    },
    
    // 加载设施并在地图上标记
    loadFacilities() {
      // 检查地图实例是否存在
      if (!this.map) {
        console.warn('地图实例未初始化，无法加载设施');
        return;
      }
      
      // 移除现有的所有标记点
      if (this.markers && this.markers.length > 0) {
        this.markers.forEach(marker => {
          marker.setMap(null);
        });
        this.markers = [];
      }
      
      // 获取要显示的设施数据
      const facilitiesToShow = this.facilities.value;
      if (!facilitiesToShow || facilitiesToShow.length === 0) {
        console.log('没有可显示的设施数据');
        return;
      }
      
      // 根据当前视图模式过滤设施
      let filteredFacilities = facilitiesToShow;
      
      // 如果设置了当前视图模式，则根据模式过滤设施
      if (this.currentViewMode !== 'all') {
        filteredFacilities = facilitiesToShow.filter(facility => {
          // 检查设施类型是否与当前视图模式匹配
          return facility.type === this.currentViewMode;
        });
      }
      
      // 开始添加标记
      console.log(`开始加载${filteredFacilities.length}个设施标记`);
      
      // 创建标记点聚合
      if (window.AMap && window.AMap.MarkerClusterer && filteredFacilities.length > 10) {
        // 当设施数量较多时使用聚合功能提高性能
        const markers = [];
        
        filteredFacilities.forEach(facility => {
          // 确保设施有有效的坐标
          if (!facility.position || !facility.position.lng || !facility.position.lat) {
            console.warn('设施缺少有效的位置信息:', facility);
            return;
          }
          
          // 创建标记点
          const marker = this.createMarker(facility);
          markers.push(marker);
        });
        
        // 创建标记聚合实例
        if (this.markerCluster) {
          this.markerCluster.setMap(null);
        }
        
        this.markerCluster = new window.AMap.MarkerClusterer(this.map, markers, {
          gridSize: 80,
          maxZoom: 18
        });
        
        this.markers = markers;
      } else {
        // 当设施数量较少时，直接添加标记点
        filteredFacilities.forEach(facility => {
          // 确保设施有有效的坐标
          if (!facility.position || !facility.position.lng || !facility.position.lat) {
            console.warn('设施缺少有效的位置信息:', facility);
            return;
          }
          
          // 创建标记点
          const marker = this.createMarker(facility);
          this.markers.push(marker);
        });
      }
      
      // 如果有标记点，调整地图视野以包含所有标记点
      if (this.markers.length > 0) {
        this.fitMapToMarkers();
      }
      
      console.log(`设施标记加载完成，共显示${this.markers.length}个标记`);
    },
    
    // 处理地图点击事件
    handleMapClick(e) {
      // 如果正在编辑设施或显示设施详情，则不响应地图点击
      if (this.editingFacility || this.showingFacilityDetail) {
        return;
      }
      
      // 获取点击位置的经纬度坐标
      const position = e.lnglat;
      console.log('地图点击位置:', position);
      
      // 如果处于添加设施模式，则弹出设施类型选择框
      if (this.addingFacility) {
        // 保存当前点击的位置
        this.clickedPosition = {
          lng: position.getLng(),
          lat: position.getLat()
        };
        
        // 显示设施类型选择模态框
        this.showFacilityTypeModal = true;
        
        // 根据当前位置获取地址信息
        this.getAddressByCoordinates(position.getLng(), position.getLat());
      } else {
        // 点击地图其他区域时，关闭可能打开的信息窗体
        this.closeInfoWindow();
      }
    },
    
    // 创建地图标记
    createMarker(facility) {
      // 确保设施有有效的类型和位置
      if (!facility.type || !facility.position) {
        console.warn('设施缺少类型或位置信息:', facility);
        return null;
      }
      
      // 获取设施类型对应的图标
      const icon = this.getFacilityIcon(facility.type);
      
      // 创建标记对象
      const marker = new window.AMap.Marker({
        position: [facility.position.lng, facility.position.lat],
        title: facility.name || '未命名设施',
        icon: icon,
        offset: new window.AMap.Pixel(-16, -16), // 图标锚点位置
        cursor: 'pointer', // 鼠标悬停样式
        draggable: false, // 默认不可拖动
        extData: facility // 存储设施数据用于事件处理
      });
      
      // 将标记添加到地图上
      marker.setMap(this.map);
      
      // 注册标记点击事件，显示设施详情
      marker.on('click', () => {
        this.showFacilityDetails(facility);
      });
      
      // 注册标记右键点击事件，显示上下文菜单
      marker.on('rightclick', (e) => {
        this.showContextMenu(e, facility);
      });
      
      return marker;
    },
    
    // 根据设施类型获取对应的图标
    getFacilityIcon(facilityType) {
      // 默认图标大小
      const size = new window.AMap.Size(32, 32);
      
      // 根据设施类型返回不同的图标
      let iconPath;
      switch (facilityType) {
        case 'hospital':
          iconPath = require('@/assets/icons/hospital.png');
          break;
        case 'school':
          iconPath = require('@/assets/icons/school.png');
          break;
        case 'restaurant':
          iconPath = require('@/assets/icons/restaurant.png');
          break;
        case 'park':
          iconPath = require('@/assets/icons/park.png');
          break;
        case 'shopping':
          iconPath = require('@/assets/icons/shopping.png');
          break;
        default:
          // 默认图标
          iconPath = require('@/assets/icons/default-marker.png');
      }
      
      // 创建并返回图标对象
      return new window.AMap.Icon({
        size: size,
        image: iconPath,
        imageSize: size
      });
    },
    
                                             // 根据坐标获取地址信息
    getAddressByCoordinates(lng, lat) {
      // 检查地图 API 是否已加载
      if (!window.AMap || !window.AMap.Geocoder) {
        console.error('地图API未加载，无法进行地理编码');
        return;
      }
      
      // 显示加载提示
      this.geoLoading = true;
      
      // 创建地理编码实例
      const geocoder = new window.AMap.Geocoder();
      
      // 调用逆地理编码API
      geocoder.getAddress([lng, lat], (status, result) => {
        // 请求完成，隐藏加载提示
        this.geoLoading = false;
        
        if (status === 'complete' && result.info === 'OK') {
          // 成功获取地址信息
          const address = result.regeocode.formattedAddress;
          console.log('获取到地址:', address);
          
          // 保存地址信息到当前位置
          this.currentAddress = address;
          
          // 如果正在添加新设施，将地址应用到表单
          if (this.newFacility) {
            this.newFacility.address = address;
          }
        } else {
          // 地理编码失败
          console.error('地理编码失败:', result);
          this.currentAddress = '地址获取失败';
          
          // 显示错误提示
          uni.showToast({
            title: '地址获取失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 显示设施详情
    showFacilityDetails(facility) {
      // 标记当前正在显示设施详情
      this.showingFacilityDetail = true;
      
      // 保存当前查看的设施
      this.selectedFacility = { ...facility };
      
      // 显示设施详情模态框
      this.showFacilityDetailModal = true;
      
      // 关闭可能已打开的信息窗体
      this.closeInfoWindow();
      
      console.log('显示设施详情:', facility);
    },
    
    // 切换视图模式
    toggleViewMode() {
      try {
        if (!this.map || !window.AMap) {
          console.warn('无法切换视图模式：地图或API未加载');
          uni.showToast({
            title: '地图未加载完成，无法切换视图模式',
            icon: 'none'
          });
          return;
        }
        
        // 切换视图模式
        const newMode = this.viewMode === '2D' ? '3D' : '2D';
        console.log(`切换视图模式: ${this.viewMode} -> ${newMode}`);
        this.viewMode = newMode;
        this.facilityStore.toggleViewMode();
        
        if (this.map) {
          // 检查地图API是否支持3D
          if (this.viewMode === '3D' && window.AMap.Map3D) {
            this.map.setViewMode('3D');
            this.map.setPitch(45); // 3D模式下的俯仰角度
          } else {
            // 如果不支持3D或切换回2D
            this.map.setViewMode('2D');
            this.map.setPitch(0);
          }
        }
      } catch (error) {
        console.error('切换视图模式失败:', error);
        uni.showToast({
          title: '视图切换失败，当前版本可能不支持',
          icon: 'none'
        });
        
        // 重置为2D模式
        this.viewMode = '2D';
        this.facilityStore.setViewMode('2D');
      }
    },
    
    // 定位到当前位置
    locateCurrentPosition() {
      if (!this.map || !window.AMap) {
        console.warn('无法定位：地图或API未加载');
        uni.showToast({
          title: '地图未加载完成，无法使用定位功能',
          icon: 'none'
        });
        return;
      }
      
      try {
        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true,
          buttonPosition: 'RB'
        });
        
        this.map.addControl(geolocation);
        
        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            console.log('定位成功:', result);
            const position = result.position;
            this.map.setCenter(position);
          } else {
            console.error('定位失败:', result);
            uni.showToast({
              title: '定位失败: ' + result.message,
              icon: 'none'
            });
          }
        });
      } catch (error) {
        console.error('定位方法执行错误:', error);
        uni.showToast({
          title: '定位服务异常',
          icon: 'none'
        });
      }
    },
    
    // 关闭天气提示
    closeWeatherTips() {
      this.showWeatherTips = false;
    },
    
    // 显示设施右键菜单
    // 根据坐标获取地址
    async getAddressByLocation(location) {
      return new Promise((resolve) => {
        if (!window.AMap || !location) {
          console.warn('无法获取地址：AMap未加载或位置无效');
          resolve('未知位置');
          return;
        }
        
        try {
          const geocoder = new window.AMap.Geocoder();
          geocoder.getAddress([location.lng, location.lat], (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              const address = result.regeocode.formattedAddress;
              console.log('获取到地址:', address);
              resolve(address);
            } else {
              console.warn('地址解析失败:', status, result);
              resolve('未知位置');
            }
          });
        } catch (error) {
          console.error('地址解析错误:', error);
          resolve('未知位置');
        }
      });
    },
    
    // 关闭天气提示
    closeWeatherTips() {
      this.showWeatherTips = false;
    },
    
    // 显示设施右键菜单
    showFacilityContextMenu(position) {
      if (!this.map || !window.AMap || !this.selectedFacility) {
        console.warn('无法显示右键菜单：地图、AMap或设施无效');
        return;
      }
      
      try {
        const contextMenu = new window.AMap.ContextMenu();
        
        contextMenu.addItem('编辑设施', () => {
          this.editFacility();
        }, 0);
        
        contextMenu.addItem('删除设施', () => {
          this.deleteFacility();
        }, 1);
        
        contextMenu.open(this.map, position);
      } catch (error) {
        console.error('显示右键菜单失败:', error);
        // 如果右键菜单失败，直接显示编辑面板
        this.editFacility();
      }
    },
    
    // 获取当前位置并在地图上标记
    getCurrentPosition() {
      if (!this.map || !window.AMap) {
        console.warn('无法获取当前位置：地图或API未加载');
        return;
      }
      
      try {
        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true,
          buttonPosition: 'RB'
        });
        
        this.map.addControl(geolocation);
        
        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            console.log('定位成功:', result);
            const position = result.position;
            this.map.setCenter(position);
          } else {
            console.error('定位失败:', result);
            uni.showToast({
              title: '定位失败: ' + result.message,
              icon: 'none'
            });
          }
        });
      } catch (error) {
        console.error('获取当前位置失败:', error);
        uni.showToast({
          title: '获取当前位置失败',
          icon: 'none'
        });
      }
    },
    
    // 加载外部脚本
    loadExternalScript() {
      // 实现加载外部脚本的功能
    },
    
    // 获取当前是否为3D模式
    getCurrent3DMode() {
      // 实现获取当前是否为3D模式的功能
    },

    showAddMarker() {
      // 获取当前地图中心点作为默认位置
      if (this.map) {
        try {
          const center = this.map.getCenter();
          const position = {
            lng: center.getLng(),
            lat: center.getLat()
          };
          
          // 保存临时位置信息
          uni.setStorage({
            key: 'temp_facility_position',
            data: JSON.stringify(position),
            success: () => {
              // 跳转到设施添加页面
              uni.navigateTo({
                url: '/pages/facility/add'
              });
            }
          });
        } catch (error) {
          console.error('获取地图中心点失败:', error);
          // 即使获取中心点失败，也跳转到添加页面
          uni.navigateTo({
            url: '/pages/facility/add'
          });
        }
      } else {
        // 如果没有地图实例，直接跳转
        uni.navigateTo({
          url: '/pages/facility/add'
        });
      }
    }
  },
  
  watch: {
    facilities: {
      handler() {
        this.loadFacilities();
      },
      deep: true
    },
    
    currentViewMode: {
      handler(newValue) {
        this.viewMode = newValue;
      },
      immediate: true
    }
  }
};
</script>

<style>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.amap-container {
  width: 100%;
  height: 100%;
}

.map-tools {
  position: absolute;
  right: 20rpx;
  bottom: 200rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tool-btn {
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 50%;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  margin-bottom: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.2s ease;
  transform: scale(1);
}

.tool-btn:active {
  transform: scale(0.92);
  background-color: rgba(245, 245, 245, 0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.add-btn {
  background: linear-gradient(135deg, #4B89FD, #3F7BFC);
  color: #fff;
  box-shadow: 0 4rpx 16rpx rgba(63, 123, 252, 0.3);
}

.add-btn:active {
  background: linear-gradient(135deg, #3F7BFC, #3062D6);
  box-shadow: 0 2rpx 8rpx rgba(63, 123, 252, 0.2);
}

.weather-tips {
  position: absolute;
  top: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  background: linear-gradient(to right, rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.65));
  color: #fff;
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  z-index: 100;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(5px);
}

.close-btn {
  margin-left: 20rpx;
  font-size: 36rpx;
  opacity: 0.8;
  transition: opacity 0.2s ease;
}

.close-btn:active {
  opacity: 1;
}

.facility-select-modal,
.facility-detail-modal,
.facility-edit-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  backdrop-filter: blur(3px);
}

.facility-select-content,
.facility-detail-content,
.facility-edit-content {
  width: 80%;
  background: linear-gradient(to bottom, #fff, #f9fafc);
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.2);
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
  text-align: center;
  color: #3F7BFC;
}

.facility-types {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.facility-type-item {
  width: 30%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
  transition: all 0.2s ease;
  transform: scale(1);
}

.facility-type-item:active {
  transform: scale(0.95);
}

.facility-icon {
  width: 50px;
  height: 50px;
  margin-bottom: 10px;
  background: linear-gradient(135deg, #4B89FD, #3F7BFC);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  box-shadow: 0 4rpx 12rpx rgba(63, 123, 252, 0.25);
  transition: all 0.2s ease;
}

.facility-type-item:active .facility-icon {
  box-shadow: 0 2rpx 6rpx rgba(63, 123, 252, 0.15);
}

.facility-icon svg {
  width: 100%;
  height: 100%;
}

.facility-icon path:not([fill="none"]) {
  fill: #fff;
}

.facility-name {
  font-size: 28rpx;
}

.modal-actions {
  display: flex;
  justify-content: space-around;
  margin-top: 40rpx;
}

.modal-actions button {
  font-size: 28rpx;
  padding: 18rpx 40rpx;
  border-radius: 50rpx;
  transition: all 0.2s ease;
  transform: scale(1);
}

.modal-actions button:active {
  transform: scale(0.95);
}

.save-btn,
.edit-btn {
  background: linear-gradient(135deg, #4B89FD, #3F7BFC);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(63, 123, 252, 0.25);
}

.save-btn:active,
.edit-btn:active {
  background: linear-gradient(135deg, #3F7BFC, #3062D6);
  box-shadow: 0 2rpx 6rpx rgba(63, 123, 252, 0.15);
}

.delete-btn {
  background: linear-gradient(135deg, #FF5A5A, #F56C6C);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(245, 108, 108, 0.25);
}

.delete-btn:active {
  background: linear-gradient(135deg, #F56C6C, #E55454);
  box-shadow: 0 2rpx 6rpx rgba(245, 108, 108, 0.15);
}

.cancel-btn,
.close-btn {
  background: linear-gradient(135deg, #F5F7FA, #F2F2F2);
  color: #666;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.cancel-btn:active,
.close-btn:active {
  background: linear-gradient(135deg, #F2F2F2, #EAEAEA);
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.facility-detail-info {
  padding: 20rpx;
  background-color: rgba(63, 123, 252, 0.05);
  border-radius: 12rpx;
}

.facility-detail-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
  color: #3F7BFC;
}

.facility-detail-desc,
.facility-detail-location {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.facility-edit-form {
  padding: 20rpx 0;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.form-input,
.form-textarea {
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: #fff;
  transition: all 0.2s ease;
}

.form-input:focus,
.form-textarea:focus {
  border-color: #3F7BFC;
  box-shadow: 0 0 0 2px rgba(63, 123, 252, 0.1);
}

.form-textarea {
  height: 200rpx;
}

.icon-svg {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-tools .tool-btn .icon-svg svg {
  width: 20px;
  height: 20px;
}

.add-btn .icon-svg path {
  fill: #fff;
}

.map-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f9fafc, #f5f7fa);
  color: #999;
  animation: pulse 1.5s infinite alternate;
}

@keyframes pulse {
  from {
    background-position: 0% 50%;
  }
  to {
    background-position: 100% 50%;
  }
}

.map-error {
  background: linear-gradient(135deg, #fff5f5, #fde8e8);
  color: #f56c6c;
  text-align: center;
}

.static-markers-container .custom-marker {
  transition: transform 0.2s ease;
}

.static-markers-container .custom-marker:hover {
  transform: scale(1.1);
}
</style> 